import axios from 'axios'

import CONFIG from "@/config/shared-config"
import object from "@/utils/object";
import qs from "qs";
import {error} from  "@/utils/msg"

const httpFactory = axios.create({
    timeout: CONFIG.REQUEST_TIME_OUT,
    //baseURL: "http://10.200.16.34/prod-api/",
    baseURL: "http://127.0.0.1:8888",
    withCredentials: false,
})



httpFactory.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'
httpFactory.defaults.crossDomain = true;

httpFactory.interceptors.request.use(config => {
    config.headers['Authorization'] = 'Bearer 432e0949e0214dd69eb2f652841b3cba';
    config.meta = {startTime: new Date()}; // 为这个请求设置开始时间
    /*CONFIG.SECURITY.TOKEN.EXCLUDE_URL.forEach((url) => {
      if (!config.url.endsWith(url)) {
        //添加认证token
        config.headers[CONFIG.TOKEN_AUTHENTICATION] = securityUtils.getToken();
      }
    });*/
    if (config.Accept == "KV") {
        config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8";
    }
    return config
}, error => {
    console.error(error)
})
httpFactory.interceptors.response.use(response => {
    // data里面的数据要解析，而params里的则不用
    const reqData = response.config.method === 'get' ? response.config.params : response.config.data;
    const resData = response.data;
    if (process.env.NODE_ENV !== 'production' && response.config.url.indexOf("sysDictData/list") == -1) {
        console.log('\n')
        const duration =  new Date() - response.config.meta.startTime; // 计算请求耗时
        console.group(response.config.method + `: ${response.config.url} 请求耗时: ${duration}ms`)
        console.log('request: ', typeof reqData === 'string' ? qs.parse(reqData) : reqData ? reqData : null)
        console.log('response: ', resData, object.clone(resData.data || null));
        console.groupEnd();
    }
    /* if (response.status === httpResponseStatus.SUCCESS) {
       if (resData.code === httpResponseStatus.SUCCESS) {
         return resData
       }
       switch (resData.code) {
         case httpResponseStatus.RESULT_STATUS_OVERTIME:
           router.push("/login")
           break;
         case httpResponseStatus.UNAUTHORIZED || httpResponseStatus.UNAUTHORIZED:
           router.push("/login")
           break
       }
       return Promise.resolve(resData)
     }*/
    return resData;
}, errors => {
    console.error('请求错误', errors)
    let {message} = errors;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    error(message);
    return Promise.reject({code: 500, data: errors})
})


export default httpFactory
